﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Security.Principal;
using System.Text;
using System.Web;

using Microsoft.Practices.Unity;
using Microsoft.Practices.Unity.Configuration;

using Moq;

using NUnit.Framework;

using ERPStore.Models;
using Serialcoder.Extensions;

namespace ERPStore.FullTextCatalog.Tests
{
	[TestFixture]
	public class TestBase
	{
		protected Microsoft.Practices.Unity.IUnityContainer m_Container;

		public virtual void Initialize()
		{
			m_Container = BootStrapper.InitializeContainer();
		}

		protected string GenerateTestName()
		{
			return Guid.NewGuid().ToString().Replace("-", "").Substring(0, 10);
		}

		protected ERPStore.Models.Product GetRandomizedProduct()
		{
			var catalogService = m_Container.Resolve<ERPStore.Services.ICatalogService>();
			var count = 0;
			ERPStore.Models.Product result = null;
			while (true)
			{
				var index = new Random(100).Next(100);
				var list = catalogService.GetProductList(index, 100, out count);
				if (list.IsNotNullOrEmpty())
				{
					var productIndex = new Random().Next(list.Count);
					result = list[productIndex];
					break;
				}
			}

			return result;
		}

		protected ERPStore.Models.User GetRandomizedUser()
		{
			var accountService = m_Container.Resolve<ERPStore.Services.IAccountService>();
			var user = accountService.GetRandomizedUserForTests();
			return user;
		}

		protected Mock<HttpContextBase> GetHttpContext()
		{
			return GetHttpContext(null);
		}
		protected Mock<HttpContextBase> GetHttpContext(UserPrincipal user)
		{
			var context = new Mock<HttpContextBase>();
			var request = new Mock<HttpRequestBase>();
			var response = new Mock<HttpResponseBase>();
			var session = new Mock<HttpSessionStateBase>();
			var server = new Mock<HttpServerUtilityBase>();

			// Our identity additions ...
			context.Setup(ctx => ctx.Request).Returns(request.Object);
			context.Setup(ctx => ctx.Request.AnonymousID).Returns(Guid.NewGuid().ToString());
			context.Setup(ctx => ctx.Response).Returns(response.Object);
			context.Setup(ctx => ctx.Session).Returns(session.Object);
			context.Setup(ctx => ctx.Server).Returns(server.Object);

			if (user != null)
			{
				context.Setup(ctx => ctx.User).Returns(user);
			}
			else
			{
				var principal = new Mock<IPrincipal>();
				var identity = new Mock<IIdentity>();
				principal.Setup(ctx => ctx.Identity).Returns(identity.Object);
				context.Setup(ctx => ctx.User).Returns(principal.Object);
			}

			return context;
		}

	}
}
